<template>
  <section class="f-order-sale">
    <div class="w-card my-content-box" v-if="!isDetail">
      <div class="title-box">
        <span class="title-text">佣金规则列表</span>
        <div style="margin-left:auto;">
          <el-button type="primary" plain @click="setOrderJoinDown()">导出</el-button>
          <el-button type="warning" plain @click="importHandle()">导入</el-button>

        </div>
      </div>
      <div class="my-search-box">
        <div>
          <span>订单ID：</span>
          <el-input v-model="searchForm.sysOrderId" clearable placeholder="请输入订单ID" />
        </div>
        <div>
          <span>关联商户：</span>
          <el-select v-model="searchForm.nameKeyword" clearable>
            <el-option v-for="item in shopList" :key="item.shopId" :label="item.shopName" :value="item.shopName" />
          </el-select>
        </div>
        <div>
          <span>订单状态：</span>
          <el-select v-model="searchForm.orderStatus" clearable>
            <el-option v-for="item in orderStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div>
          <span>提现方式：</span>
          <el-select v-model="searchForm.payType" clearable>
            <!-- <el-option label="微信" value="2" /> -->
            <el-option label="支付宝" value="3" />
            <el-option label="银行卡" value="11" />
          </el-select>
        </div>
      </div>
      <div class="my-search-box">
        <div class="datebox">
          <span>操作时间：</span>
          <el-date-picker v-model="searchForm.date" type="datetimerange" value-format="x" start-placeholder="开始时间"
            end-placeholder="结束时间" @change="(e) => {console.log(e)}" />
        </div>
        <div class="f-ml-20">
          <el-button @click="searchHandle" type="primary">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
      </div>

      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe>
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="orderId" label="订单ID" align="center">
            <template v-slot="scope">
              <el-link style="font-size:12px" type="primary" @click="lookDetail(scope.row)">
                {{ scope.row.sysOrderId || '' }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="uniqueName" label="商户名称" align="center">
            <template v-slot="scope">
              {{ scope.row.uniqueName || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="payType" label="提现方式" align="center">
            <template v-slot="scope">
              {{ payType[scope.row.payType] }}
            </template>
          </el-table-column>
          <el-table-column prop="toAccount" label="收款账号" align="center">
            <template v-slot="scope">
              {{ scope.row.toAccount || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="totalMoney" label="申请金额（元）" align="center">
            <template v-slot="scope">
              {{ scope.row.totalMoney }}
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" align="center">
            <template v-slot="scope">
              {{ orderStatus[scope.row.orderStatus] }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="操作时间" align="center">
            <template v-slot="scope">
              {{ getDateTime(scope.row.createTime)[6] || '--' }}
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 导入弹窗 -->
    <Upload ref="uploadRef" v-if="off.upload" :uploadForm="uploadForm" @handleUploadSuccess="importSuccess"
      @handleUploadCancel="off.upload = false" />

    <router-view></router-view>
  </section>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad, setStore } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import Upload from '@/components/Upload.vue'
import api from '../api'

export default {
  components: { Upload },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const uploadRef = ref(null)

    const state = reactive({
      loading: false,
      off: {
        upload: false,
      },
      isDetail: false,

      searchForm: {
        "orderStatus": '',
        "payType": '',
        "nameKeyword": '',
        "sysOrderId": "",
        "timeMax": '',
        "timeMin": ''
      },

      tableHeight: 0,
      tableData: [],
      page: 1,
      size: 10,
      total: 0,

      orderStatusOptions: [
        { value: 1, label: '发起提现' },
        { value: 2, label: '已关闭' },
        { value: 3, label: '提现失败' },
        { value: 4, label: '提现成功' },
      ],
      orderStatus: {
        '1': '发起提现',
        '2': '已关闭',
        '3': '提现失败',
        '4': '提现成功',
        '5': '待人工处理'
      },

      shopList: [],

      uploadForm: {
        dialogTitle: '导入提现订单',
        action: '/eas/manage/withdraw/import',
        seletMonth: true
      },

      payType: {
        '2': '微信',
        '3': '支付宝',
        '11': '银行卡'
      }
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/orderWithdraw')
      getTableData()
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {}
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
        timeMin: state.searchForm.date && state.searchForm.date[0],
        timeMax: state.searchForm.date && state.searchForm.date[1],
        orderBy: 'id desc',
      }
      api.orderWithdraw(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.list
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function lookDetail(data) {
      router.push({
        path: '/orderWithdraw/detail', query: {
          sysOrderId: data.sysOrderId,
        }
      })
    }

    const setOrderJoinDown = () => {
      let json = JSON.parse(JSON.stringify(state.searchForm))
      json.orderStatus = 1
      const obj = {
        page: state.page,
        size: state.size,
        ...json,
        timeMin: state.searchForm.date && state.searchForm.date[0],
        timeMax: state.searchForm.date && state.searchForm.date[1],
        orderBy: 'id desc',
        responseType: 'blob',
      }
      state.loading = true
      api.orderWithdrawDown(obj).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
        state.loading = false
        successDeal('导出成功！')
      }).catch(err => {
        console.log(err)
        state.loading = false
      })
    }

    //导入成功
    function importSuccess() {
      state.page = 1
      getTableData()
    }

    function importHandle() {
      state.off.upload = true
      nextTick(() => {
        uploadRef.value.off.dialog = true
      })
    }

    const getShopAll = () => {
      api.shopAll().then(res => {
        state.shopList = res.data
      })
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 330
      setIsDetail()
      getShopAll()
    })

    return {
      ...toRefs(state),
      uploadRef,
      searchHandle,
      resetHandle,
      lookDetail,
      handleCurrentChange,
      handleSizeChange,
      getDateTime,
      setOrderJoinDown,
      importSuccess,
      importHandle,
    }
  }
}
</script>

<style lang="scss" scoped>
.f-order-sale {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    > .title-box {
      display: flex;
      align-items: center;

      > .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 300px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 90px;
          text-align: right;
        }
      }

      .datebox {
        width: 400px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: space-around;
        align-items: center;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
}
</style>